package com.yx.frame.server;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.yx.frame.service.ActionManager;
import com.yx.frame.service.Action;
import com.yx.frame.authority.AuthorityManager;
import com.yx.frame.jdbc.pool.JdbcConfig;
import com.yx.frame.jdbc.pool.PoolManager;
import com.yx.frame.log.LogFactory;
import com.yx.frame.web.AsyncServiceExecutor;
import com.yx.frame.web.WebServer;

public final class Application {
	
	static Provider provider=null;
	
	public static Provider getProvider() {
		return provider;
	}

	public Application() {
	}

	public static void startAppServer(String externalControllerClassName,List<JdbcConfig> jdbcConfig, Action[] actions,
			int logLevel,boolean startJety,boolean isJDK18,int port,int minThreadPoolSize,
			int maxThreadPoolSize,
			int minAsyncThreadPoolSize,
			int maxAsyncThreadPoolSize,int maxUploadFileSize,long authorityTimeDifference ) {
		try {
			Properties pps = System.getProperties();
			pps.put("file.encoding", "UTF-8");
			System.out.println("JVM file.encoding="	+ pps.getProperty("file.encoding"));
			LogFactory.SYSTEM_LOG_level = logLevel;
			minThreadPoolSize=minThreadPoolSize>10?minThreadPoolSize:10;
			maxThreadPoolSize=maxThreadPoolSize>30?maxThreadPoolSize:30;
			minAsyncThreadPoolSize=minAsyncThreadPoolSize>10?minAsyncThreadPoolSize:10;
			maxAsyncThreadPoolSize=maxAsyncThreadPoolSize>20?maxAsyncThreadPoolSize:20;
			System.out.println("Maximum upload file="+maxUploadFileSize+"M");
			System.out.println("Web Server thread pool =("+minThreadPoolSize+"-"+maxThreadPoolSize+"),Asynchronous thread pool=("+minAsyncThreadPoolSize+"-"+maxAsyncThreadPoolSize+")");
			AsyncServiceExecutor.init(maxAsyncThreadPoolSize);
			PoolManager.getInstance().init(jdbcConfig);
			provider=(Provider)Class.forName(externalControllerClassName).newInstance();
			ActionManager.getInstace().setActions(actions);
			AuthorityManager.getInstance().setTimeDifference(authorityTimeDifference);
			WebServer.maxFileSize=maxUploadFileSize*1024*1024;
			if (startJety) {
				WebServer server = new WebServer(port,minThreadPoolSize,maxThreadPoolSize);
				server.start(isJDK18);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static int getParmInt(String[] args, String key) {
		try {
			List<String> parm = new ArrayList<String>();
			for (int i = 0; i < args.length; i++) {
				String arg = args[i].trim();
				if (arg.startsWith(key + "=")) {
					return Integer.parseInt(arg.substring(key.length() + 1));
				}
			}
			return -1;
		} catch (Exception e) {
			return -1;
		}
	}

}
